/**
 * role manage class,it contains role definition and new/modify/delete role functions
 * Fuzhou Huilin corp.ltd 2016.03.29
 * last update by lynmison@126.com 2016.03.29
 **/
package com.fzrskj.cloud.free.sys.dao;

import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.CloudDbDrvUtils;
import com.fzrskj.cloud.free.sys.bean.Role;
import com.winiis.component.common.utils.db.DbUtils;
import ms.core.consts.SysErr;
import ms.core.db.IDbDrv;
import ms.core.object.CObject;
import ms.core.tool.StrTool;
import net.sf.json.JSONArray;

import java.util.Date;
import java.util.List;

public class CRoleDao extends CObject {
    //private declaration
    IDbDrv db = null;

    //constructor function to initialize database
    public CRoleDao() {
        db = CloudDbDrvUtils.getDbUtilsDrv();
    }

    //dispose function implements to free database resource
    @Override
    public void dispose() {
        super.dispose();
        db.closeConnection();
        db = null;
    }

    //new role
    public int newRole(Role role) {
        Role r = queryRole(role.getRoleName());
        if (r != null) {
            this.setErrCode(SysErr.USER_ROLE_EXISTS);
            return 0;
        }

        role.setCreateTime(new Date());
        String strSql = "insert into sys_role(roleName,roleCName,remark,createTime,agentId) values(?,?,?,?,?)";
        Object[] param = {role.getRoleName(), role.getRoleCName(), role.getRemark(), role.getCreateTime(), CloudContextUtils.getAgentId()};
        int ret = db.executeSql(strSql, param);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        setErrCode(err);
        if (ret > 0) {
            role.setId(DbUtils.lastId(this.db));
            ret = role.getId();
        }
        return ret;
    }

    //delete role by roleId
    public int delRole(int roleId) {
        String strSql = String.format("delete from sys_role where id=%d and agentId=%d", roleId, CloudContextUtils.getAgentId());
        int ret = db.executeSql(strSql);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        setErrCode(err);
        return ret;
    }

    //delete role by roleName
    public int delRole(String roleName) {
        String strSql = String.format("delete from sys_role where roleName='%s' and agentId=%d", roleName, CloudContextUtils.getAgentId());
        int ret = db.executeSql(strSql);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        setErrCode(err);
        return ret;
    }

    //modify role information
    public int modRole(int id, String cname, String remark) {
        String strSql = "update sys_role set roleCName=?,remark=? where id=? and agentId=?";
        Object[] param = {cname, remark, id, CloudContextUtils.getAgentId()};
        int ret = db.executeSql(strSql, param);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        setErrCode(err);
        return ret;
    }

    //to query role by role name
    public Role queryRole(String roleName) {
        String sql = "select * from sys_role where roleName=? and agentId=?";
        Object[] params = {roleName, CloudContextUtils.getAgentId()};
        Role r = db.queryForBean(sql, Role.class, params);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        setErrCode(err);
        return r;
    }

    //to query all role
    public List<Role> queryRole(int roleId) {
        String strSql = "select * from sys_role where agentId=" + CloudContextUtils.getAgentId();
        if (roleId > 0) {
            strSql = String.format("select * from sys_role where id=%d and agentId=%d", roleId, CloudContextUtils.getAgentId());
        }
        List<Role> ret = db.queryForBeans(strSql, Role.class);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        setErrCode(err);
        return ret;
    }

    //to set role functions
    public int setRoleFun(int id, String funs) {
        String sql = "update sys_role set funcs=? where id=? and agentId=?";
        Object[] params = {funs, id, CloudContextUtils.getAgentId()};
        int ret = db.executeSql(sql, params);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(err);
        return ret;
    }

    /**
     * to query role's functions
     *
     * @param roleAry, the format is "[{"id":"admin"},{"id":"xxx"}...]"
     * @return null or json string of functions, such as "[{"id":"fun1"},{"id":"fun2"}...]"
     */
    public String queryRoleFunc(String roleAry) {
        if (StrTool.isBlankStr(roleAry)) {
            return null;
        }

        JSONArray aryRole = CJsonTool.getJsonArray(roleAry);
        if (aryRole == null) {
            return null;
        }

        String roleName;
        String strSql = "select * from sys_role where 1>0  and agentId=" + CloudContextUtils.getAgentId() + " and (";
        for (int i = 0; i < aryRole.size(); i++) {
            roleName = (String) CJsonTool.getJsonArrayValue(aryRole, i, "id");
            if (i == aryRole.size() - 1) {
                strSql = strSql + String.format(" roleName='%s')", roleName);
            } else {
                strSql = strSql + String.format(" roleName='%s' or ", roleName);
            }
        }
        List<Role> roles = db.queryForBeans(strSql, Role.class);
        String err = db.getErrCode();
        if (!err.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        setErrCode(err, codeOfMsg(err));
        if (roles == null) {
            return null;
        }

        JSONArray ret = new JSONArray();
        for (int i = 0; i < roles.size(); i++) {
            JSONArray funs = CJsonTool.getJsonArray(roles.get(i).getFuncs());
            if (funs == null) {
                continue;
            }

            for (int j = 0; j < funs.size(); j++) {
                CJsonTool.addObjToJsonArray(ret, funs.get(j));
            }
        }
        return ret.toString();
    }

}
